﻿using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using SU.Center.Domain.RBAC;
using SU.Center.Infa;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SU.Center.Api.Handler.RBAC
{
    /// <summary>
    /// 用户登录
    /// </summary>
    public class GetUserLogHandler : IRequestHandler<GetUserLogRepsultDto, ApiResult>
    {
        private readonly ILogger<GetUserLogHandler> logger;
        private readonly IBaseReposiotry<UserInfo> userLogRepository;
        private readonly IJwtTokenGenerator jwtTokenGenerator;
        private readonly IMapper mapper;

        public GetUserLogHandler(ILogger<GetUserLogHandler> logger, IBaseReposiotry<UserInfo> userLogRepository, IMapper mapper, IJwtTokenGenerator jwtTokenGenerator)
        {
            this.logger = logger;
            this.userLogRepository = userLogRepository;
            this.mapper = mapper;
            this.jwtTokenGenerator = jwtTokenGenerator;
        }

        public async Task<ApiResult> Handle(GetUserLogRepsultDto request, CancellationToken cancellationToken)
        {
            var list = await userLogRepository.GetAsync(x => x.UserName == request.UserName);

            if (list == null)
            {
                return ApiResult.Error("用户不存在");
            }
            if (list.Password != request.Password)
            {
                return ApiResult.Error("密码错误");
            }
            var users = userLogRepository.UpdateAsync(list);
            var list2 = mapper.Map<GetUserLogReesoupDto>(list);
            list2.Token = jwtTokenGenerator.GenerateToken(list.UserInfoId, list.UserName);
            return await Task.FromResult(ApiResult.Ok(list2));
        }
    }


}

public class GetUserLogRepsultDto : IRequest<ApiResult>
{
    /// <summary>
    /// 用户名
    /// </summary>
    public string UserName { get; set; }
    /// <summary>
    /// 密码
    /// </summary>
    public string Password { get; set; }
}

public class GetUserLogReesoupDto
{
    /// <summary>
    /// 用户Id
    /// </summary>
    public int UserInfoId { get; set; }
    /// <summary>
    /// 用户名
    /// </summary>
    public string UserName { get; set; }
    /// <summary>
    /// 密码
    /// </summary>
    public string Password { get; set; }
    /// <summary>
    /// Token
    /// </summary>
    public string Token { get; set; }
}
